package com.itobase.questionnaire.service.impl;

import com.itobase.questionnaire.model.EnumList.MOItem;
import com.itobase.questionnaire.model.Survey;
import com.itobase.questionnaire.repository.SurveyRepository;
import com.itobase.questionnaire.service.IUrlService;
import com.itobase.questionnaire.util.MD5Util;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.ser.BeanDeserializerFactory;
import org.apache.axis.encoding.ser.BeanSerializerFactory;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.namespace.QName;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author liucong
 * @date 2018/8/6
 */

@org.springframework.stereotype.Service
public class UrlService implements IUrlService {

    @Autowired
    SurveyRepository surveyRepository;
    private Logger logger = LoggerFactory.getLogger(getClass());
    static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String sendMessage(String numbers,String content) {
        // TODO: 2018/8/6 send message to client
        String number[]=numbers.split(",");
        for(int i=0;i<number.length;i++){
            try {
                HttpURLConnection connection=(HttpURLConnection)new URL("http://122.229.30.151:8282/gxtMsgService/services/SendMsg").openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
                connection.setRequestProperty("soapaction","");
                connection.connect();//连接服务器
                OutputStream os=connection.getOutputStream();
                SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
                Date date1 = new Date(System.currentTimeMillis());
                Integer date=Integer.parseInt(formatter.format(date1));
                Integer pwd=88071024;
                Integer merge=date&pwd;
                String mergeS=merge.toString();
                while(mergeS.length()<6){
                    mergeS="0"+mergeS;
                }
                System.out.println(mergeS);
                mergeS=mergeS.substring(mergeS.length()-6,mergeS.length());
                mergeS= MD5Util.getMD5(mergeS);
                String prefix="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.pubinfo.com.cn\">\n" +
                        "   <soapenv:Header/>\n" +
                        "   <soapenv:Body>\n" +
                        "      <ser:sendMsg>\n" +
                        "         <ser:in0>28877777</ser:in0>\n" ;
                String pwd1="<ser:in1>"
                        +mergeS+
                        "</ser:in1>\n" +
                        "<ser:in2>"+number[i]+"</ser:in2>\n" +
                        "<ser:in3>"+content+"</ser:in3>\n" ;
                String  suffix="</ser:sendMsg>\n" +
                        "   </soapenv:Body>\n" +
                        "</soapenv:Envelope>";
                String body=prefix+pwd1+suffix;
                os.write(body.getBytes());
                os.flush();
                os.close();
                InputStream is = connection.getInputStream();//获取数据，真正的请求从此处开始
                byte[] bts=new byte[is.available()];
                is.read(bts);
                Document doc= DocumentHelper.parseText(new String(bts));
                Element rootElt = doc.getRootElement(); // 获取根节点
                Map<String,String> map = new HashMap();
                map.put("soap",rootElt.getNamespaceURI());
                map.put("ns1","http://service.pubinfo.com.cn");
               // System.out.println(rootElt.getNamespaceURI());
                XPath xPath = doc.createXPath("//soap:Body//ns1:sendMsgResponse//ns1:out");
                xPath.setNamespaceURIs(map);
                Node node = xPath.selectSingleNode(doc);
                logger.warn("sendTo:{} :{} result:{}",number[i],content.substring(20,25),node.getText());
                if(i%10==0){
                    TimeUnit.SECONDS.sleep(6);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch (DocumentException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "Success";
    }




    @Override
    public void sendTest(List<String> list, String surveyId){
        try {
            Survey survey = surveyRepository.findOne(surveyId);
            /**
             * 补发短信
             */
            survey.getUserList_informed().addAll(survey.getUserList());
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                String phoneNumber = list.get(i);
                if (i == 0) {
                    stringBuffer.append(phoneNumber);
                } else {
                    stringBuffer.append("," + phoneNumber);
                }
            }

            System.out.println(stringBuffer.toString());

            String url = survey.getUrl().substring(7);
            String wsdlUrl = "http://211.138.112.183/smsinterface/services/GaoxtSMSInterfaceForSchools?wsdl ";
            String nameSpaceUri = "http://211.138.112.183/smsinterface/services/GaoxtSMSInterfaceForSchools";
            // 创建调用对象
            Service service = new Service();
            Call call = (Call) service.createCall();
            QName qn = new QName("http://211.138.112.183/smsinterface/services/GaoxtSMSInterfaceForSchools", "moitem");
            call.registerTypeMapping(MOItem.class, qn, new BeanSerializerFactory(MOItem.class, qn), new BeanDeserializerFactory(MOItem.class, qn));
            // 调用getMessage
            call.setOperationName(new QName(nameSpaceUri, "sendSMSByMp"));
            call.setTargetEndpointAddress(new java.net.URL(wsdlUrl));
            //int ret = (Integer)call.invoke(new Object[] {});
            String loginName = "zjgsu-fzghc";
            String passWord = "28877526qym";
            String schoolCode = "10353";
            String smsMsg = "您好，您已被浙江工商大学任期目标管理工作领导小组办公室发布的“" + survey.getTitle() + "”测试抽中,请点击 " + url + " 进行答题，账号为您的学号/工号，密码为此手机号";
            String sendTime = format.format(new Date());
            String mpNumber = stringBuffer.toString();
            long userDefId = 2;
            //MOItem[] MOItems = (MOItem[]) call.invoke(new Object[]{loginName,passWord,schoolCode});
            Object ret = (Object) call.invoke(new Object[]{loginName, passWord, schoolCode, smsMsg, sendTime, mpNumber, userDefId});
            String str = ret.toString();
            System.out.println("return value is" + str);
            if (str.equals("0")) {
                surveyRepository.save(survey);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public String send_2(String numbers,String content){
        try {
            String wsdlUrl = "http://211.138.112.183/smsinterface/services/GaoxtSMSInterfaceForSchools?wsdl ";
            String nameSpaceUri = "http://211.138.112.183/smsinterface/services/GaoxtSMSInterfaceForSchools";
            // 创建调用对象
            Service service = new Service();
            Call call = (Call)service.createCall();
            QName qn = new QName("http://211.138.112.183/smsinterface/services/GaoxtSMSInterfaceForSchools","moitem");
            call.registerTypeMapping(MOItem.class, qn, new BeanSerializerFactory(MOItem.class,qn), new BeanDeserializerFactory(MOItem.class,qn));
            // 调用getMessage
            call.setOperationName(new QName(nameSpaceUri, "sendSMSByMp"));
            call.setTargetEndpointAddress(new java.net.URL(wsdlUrl));
            //int ret = (Integer)call.invoke(new Object[] {});
            String loginName = "zjgsu-fzghc";
            String passWord = "28877526qym";
            String schoolCode = "10353";
            String smsMsg = content;
            String sendTime = format.format(new Date());
            String mpNumber = numbers;
            long userDefId = 2;
            //MOItem[] MOItems = (MOItem[]) call.invoke(new Object[]{loginName,passWord,schoolCode});
            Object ret = (Object)call.invoke(new Object[] {loginName,passWord,schoolCode,smsMsg,sendTime,mpNumber,userDefId});
            String value = ret.toString();
            System.out.println("return value is"+value);
            return value;
        }catch(Exception ex){
            ex.printStackTrace();
            return "0";
        }
    }
}


